package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.to.HasStockTo;
import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.SpuBoundTo;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.dao.SpuInfoDescDao;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.feign.SearchFeignService;
import com.atguigu.gulimall.product.feign.WareFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Resource
    private SpuInfoDescService spuInfoDescService;
    @Resource
    private SpuImagesService spuImagesService;

    @Resource
    private AttrService attrService;
    @Resource
    private ProductAttrValueService productAttrValueService;
    @Resource
    private SkuInfoService skuInfoService;
    @Resource
    private SkuImagesService skuImagesService;
    @Resource
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Resource
    private CouponFeignService couponFeignService;
    @Resource
    private BrandService brandService;
    @Resource
    private CategoryService categoryService;
    @Resource
    private WareFeignService wareFeignService;
    @Resource
    private SearchFeignService searchFeignService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        //1.保存spu 基本信息 pms_spu_info
        SpuInfoEntity infoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo,infoEntity);
        infoEntity.setCreateTime(new Date());
        infoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(infoEntity);

        //2.保存spu的描述图片 pms_spu_info_desc
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setDecript(String.join(",",decript));
        descEntity.setSpuId(infoEntity.getId());
        spuInfoDescService.save(descEntity);

        //3.保存spu的图片集  pms_spu_images
        List<String> images = vo.getImages();
        spuImagesService.saveImages(infoEntity.getId(),images);

        //4.保存spu的规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setAttrId(attr.getAttrId());
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            valueEntity.setAttrName(attrEntity.getAttrName());
            valueEntity.setAttrValue(attr.getAttrValues());
            valueEntity.setQuickShow(attr.getShowDesc());
            valueEntity.setSpuId(infoEntity.getId());

            return valueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(collect);

        //5.保存spu的积分信息：gulimall_sms: sms_spu_bounds
        Bounds bounds = vo.getBounds();
        SpuBoundTo boundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds,boundTo);
        boundTo.setSpuId(infoEntity.getId());
        R r1 = couponFeignService.saveSpuBounds(boundTo);
        if(r1.getCode()!=0){
            log.error("远程保存spu积分信息失败");
        }

        //6.保存当前spu对应的sku信息：
        List<Skus> skus = vo.getSkus();
        if(skus!=null&&skus.size()>0){
            //6.1)、sku的基本信息：pms_sku_info
            skus.forEach(sku->{
                String defaultImg = "";
                for (Images image : sku.getImages()) {
                    if (image.getDefaultImg()==1) {
                        defaultImg = image.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku,skuInfoEntity);
                skuInfoEntity.setBrandId(infoEntity.getBrandId());
                skuInfoEntity.setCatalogId(infoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(infoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.save(skuInfoEntity);

                //6.2)、sku的图片信息：pms_sku_images
                Long skuId = skuInfoEntity.getSkuId();
                List<SkuImagesEntity> imagesEntities = sku.getImages().stream().map(img -> {
                    SkuImagesEntity imagesEntity = new SkuImagesEntity();
                    imagesEntity.setSkuId(skuId);
                    imagesEntity.setImgUrl(img.getImgUrl());
                    imagesEntity.setDefaultImg(img.getDefaultImg());
                    return imagesEntity;
                }).filter(entity->{
                    //返回true就是需要，false就是剔除
                    return StringUtils.isNotBlank(entity.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(imagesEntities);

                //6.3)、sku的销售属性信息 ：pms_sku_sale_attr_value
                List<Attr> attr = sku.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                //6.4)、sku的优惠、满减等信息  gulimall_sms -> sms_sku_ladder\sms_sku_full_reduction\sms_member_price
                SkuReductionTo reductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku,reductionTo);
                reductionTo.setSkuId(skuId);
                if(reductionTo.getFullCount()>0 || reductionTo.getFullPrice().compareTo(new BigDecimal(0))==1){
                    R r = couponFeignService.saveSkuReduction(reductionTo);
                    if(r.getCode()!=0){
                        log.error("远程保存sku优惠信息失败");
                    }
                }

            });
        }



    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity infoEntity) {
        save(infoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        LambdaQueryWrapper<SpuInfoEntity> wrapper = new LambdaQueryWrapper<>();
        String catalogId = (String)params.get("catalogId");
        String status = (String)params.get("status");
        String key = (String)params.get("key");
        String brandId = (String)params.get("brandId");
        if(StringUtils.isNotBlank(key)){
            wrapper.and(w->{
                w.like(SpuInfoEntity::getSpuName,params.get("key"))
                        .or().eq(SpuInfoEntity::getId,params.get("key"));
            });
        }
        if(StringUtils.isNotBlank(catalogId)&&!"0".equals(catalogId)){
                wrapper.eq(SpuInfoEntity::getCatalogId,catalogId);
        }
        if(StringUtils.isNotBlank(status)){
                wrapper.eq(SpuInfoEntity::getPublishStatus,status);
        }
        if(StringUtils.isNotBlank(brandId)&&!"0".equals(brandId)){
                wrapper.eq(SpuInfoEntity::getBrandId,brandId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params), wrapper
        );

        return new PageUtils(page);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void up(Long spuId) {
        //组装需要的数据

        //todo 4、查询当前sku的所有可以被用来检索的规格属性
        List<ProductAttrValueEntity> valueEntities = productAttrValueService.listForSpu(spuId);

        List<Long> longList = valueEntities.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());


        List<Long> searchAttrs = attrService.selectSearchAttrs(longList);

        Set<Long> ids = new HashSet<>(searchAttrs);

        List<SkuEsModel.Attrs> collect = valueEntities.stream().filter(item -> {
            return ids.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attr = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item,attr);
            return attr;
        }).collect(Collectors.toList());

        //todo 1.发送远程调用，库存系统查询是否有库存
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);
        Map<Long, Boolean> map =null;
        //查出所有的skuId
        List<Long> list = skus.stream().map(item -> {
            return item.getSkuId();
        }).collect(Collectors.toList());
        try{
            R skuStock = wareFeignService.getSkuStock(list);
            TypeReference<List<HasStockTo>> objectTypeReference = new TypeReference<List<HasStockTo>>(){};
            map = skuStock.getData(objectTypeReference).stream().collect(Collectors.toMap(HasStockTo::getSkuId, HasStockTo::getHasStock));
        }catch (Exception e){
            e.printStackTrace();
            log.error("库存系统查询失败",e);
            throw e;
        }

        //1、查出当前spuId对应的所有sku信息，品牌的名字

        //2、封装每个sku的信息
        Map<Long, Boolean> finalMap = map;
        List<SkuEsModel> modelList = skus.stream().map(item -> {
            SkuEsModel esMode = new SkuEsModel();
            BeanUtils.copyProperties(item,esMode);
            esMode.setSkuPrice(item.getPrice());
            esMode.setSkuImg(item.getSkuDefaultImg());

            //设置库存信息
            if(finalMap!=null){
                esMode.setHasStock(finalMap.get(item.getSkuId()));
            }else {
                esMode.setHasStock(false);
            }


            //todo 2.热度评分，刚上架时 0
            esMode.setHotScore(0L);
            //todo 3.查询品牌和分类信息
            BrandEntity brandEntity = brandService.getById(esMode.getBrandId());
            esMode.setBrandName(brandEntity.getName());
            esMode.setBrandImg(brandEntity.getLogo());
            CategoryEntity categoryEntity = categoryService.getById(esMode.getCatalogId());
            esMode.setCatalogName(categoryEntity.getName());

            //todo 4、查询当前sku的所有规格属性
            esMode.setAttrs(collect);
            return esMode;
        }).collect(Collectors.toList());

        R r = searchFeignService.productStatusUp(modelList);
        if(r.getCode()==0){
            //远程调用成功
            //todo 6、修改spu 状态
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else {
            //远程调用失败
            //TODO 重复调用，接口幂等性，重试机制？
        }

    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity skuInfoEntity = skuInfoService.getById(skuId);
        Long spuId = skuInfoEntity.getSpuId();
        SpuInfoEntity spuInfoEntity = baseMapper.selectById(spuId);
        return spuInfoEntity;
    }


}